﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Configuration;
using System.Diagnostics;
using System.Text;

namespace Derrick.Web
{
    public partial class CometProxy : System.Web.UI.Page
    {

        private TraceSwitch _proxySwitch = new TraceSwitch("CometProxy", "CometProxy");

        protected void Page_Load(object sender, EventArgs e)
        {

            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Entering CometProxy.Page_Load().");
            byte[] bytes;
            using (Stream reader = Request.GetBufferlessInputStream())
            {
                bytes = new byte[reader.Length];
                reader.Read(bytes, 0, (int)reader.Length);
            }

            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Building HTTP request to Comet.");
            string newUrl = ConfigurationManager.AppSettings["CometServer"];
            HttpWebRequest cometRequest = (HttpWebRequest)HttpWebRequest.Create(newUrl);

            cometRequest.SendChunked = false;
            cometRequest.KeepAlive = true;
            //cometRequest.Credentials = new NetworkCredential("server", "server123");
            cometRequest.Method = Request.HttpMethod;
            cometRequest.ContentType = Request.ContentType;
            cometRequest.UserAgent = Request.UserAgent;
            if (bytes.Length > 0)
            {
                cometRequest.ContentLength = bytes.Length;
            }
            else
            {
                cometRequest.ContentLength = 0;
            }

            bool containsOriginHeader = false;
            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Checking for Origin header.");

            for (int i = 0; i < Request.Headers.Count; i++)
            {
                if (Request.Headers.GetKey(i).Equals("Origin"))
                {
                    containsOriginHeader = true;
                    break;
                }
            }

            if (containsOriginHeader)
            {
                //cometRequest.Headers["Origin"] = Request.Headers["Origin"];
                cometRequest.Headers.Set("Origin", Request.Headers["Origin"]);
            }
            else
            {
                cometRequest.Headers.Add("Origin", Request.Url.AbsoluteUri);
            }

            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Adding Origin header.");

            Stream stream = null;

            if (cometRequest.ContentLength > 0 && !cometRequest.Method.Equals("OPTIONS"))
            {
                stream = cometRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
            }

            if (stream != null)
            {
                stream.Close();
            }

            //Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Forwarding message: " + System.Text.Encoding.ASCII.GetString(bytes));

            try
            {
                Response.ClearHeaders();
                HttpWebResponse res = (HttpWebResponse)cometRequest.GetResponse();
                for (int i = 0; i < res.Headers.Count; i++)
                {
                    string headerName = res.Headers.GetKey(i);
                    //Response.Headers.Set(headerName, res.Headers[headerName]);
                    Response.AddHeader(headerName, res.Headers[headerName]);
                }

                System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Added headers.");

                Stream s = res.GetResponseStream();

                string msgSizeStr = ConfigurationManager.AppSettings["MessageSize"];
                int messageSize = Convert.ToInt32(msgSizeStr);

                byte[] read = new byte[messageSize];
                // Reads 256 characters at a time.    
                int count = s.Read(read, 0, messageSize);
                while (count > 0)
                {
                    // Dumps the 256 characters on a string and displays the string to the console.
                    byte[] actualBytes = new byte[count];
                    Array.Copy(read, actualBytes, count);
                    //Response.BinaryWrite(actualBytes);
                    //string cometResponseStream = Encoding.UTF8.GetString(actualBytes);
                    string cometResponseStream = Encoding.ASCII.GetString(actualBytes);
                    //Response.Write(actualBytes);
                    Response.Write(cometResponseStream);
                    count = s.Read(read, 0, messageSize);
                }

                Response.End();
                System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Sent Message.");

                s.Close();
            }
            catch (Exception ex)
            {
                //Console.WriteLine(e.Message);
                System.Diagnostics.Trace.WriteLine("CometProxy Exception: " + ex.ToString());

            }



            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Leaving CometProxy.Page_Load().");
            System.Diagnostics.Trace.Flush();
            System.Diagnostics.Trace.Close();
        }



    }
}